﻿using System;
using System.Diagnostics;
using Sustainalytics.Utils;
using System.Collections.Generic;
using Sustainalytics.Entities;
using System.IO;

namespace Sustainalytics.ReportGenerator.BL
{
    public class ReportGenerator : IReportGenerator
    {
        public RenderResult[] GenerateReportPdf(CompanyReportDataOffline crdo, bool useParallelism, bool bulkGeneration = false)
        {
            var sw = Stopwatch.StartNew();

            var clientReportPdfRenderer = new PdfReportRenderer(crdo, useParallelism, bulkGeneration);
            var pdfDocuments = clientReportPdfRenderer.GetPdfDocument();

            sw.Stop();

            var renderResults = new List<RenderResult>
            {
                new RenderResult
                {
                    Id = Guid.NewGuid(),
                    CompanyId = crdo.CompanyId,
                    ReportType = crdo.ReportType,
                    FileName = GetFileName(crdo),
                    FileType = FileType.Pdf,
                    FileContent = pdfDocuments[0],
                    RenderDuration = sw.Elapsed
                }
            };

            if (!bulkGeneration || (crdo.ReportType != ReportType.CoreReport && crdo.ReportType != ReportType.ComprehensiveReport))
                return renderResults.ToArray();

            crdo.ReportType = GetSummaryReportType(crdo.ReportType);

            renderResults.Add(new RenderResult
            {
                Id = Guid.NewGuid(),
                CompanyId = crdo.CompanyId,
                ReportType = crdo.ReportType,
                FileName = GetFileName(crdo),
                FileType = FileType.Pdf,
                FileContent = pdfDocuments[1],
                RenderDuration = sw.Elapsed
            });
            return renderResults.ToArray();
        }
        
        private static string GetFileName(CompanyReportDataOffline crdo)
        {
            var companyName = crdo.CorporateData.CompanyName;
            return crdo.ReportType.GetFullReportName(companyName, crdo.CompanyId);
        }

        private static ReportType GetSummaryReportType(ReportType reportType)
        {
            switch (reportType)
            {
                case ReportType.CoreReport:
                    return ReportType.SummaryCoreReport;
                case ReportType.ComprehensiveReport:
                    return ReportType.SummaryComprehensiveReport;
                default:
                    throw new ArgumentOutOfRangeException(nameof(reportType), reportType, null);
            }
        }
    }
}
